<?php

function plant_info_add_page($id)
{
    return drupal_get_form('plant_info_edit_form',$id);
}

function plant_info_edit_page($id)
{
    return drupal_get_form('plant_info_edit_form', $id);
}

function plant_info_edit_form($form, &$form_state)
{
    if (!empty($_GET['farmer_id'])) {
        $form_state['farmer'] = $_GET['farmer_id'];
    }
    if (!empty($form_state['farmer'])) {
        $form['#farmer'] = $form_state['farmer'];
    }

    drupal_add_js(drupal_get_path('module', 'fertilizer_case') . '/fertilizer_case_add_sub_extra.js', 'file');
    global $user;
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if (!empty($id)) {
        $record = nonghua_data_load('plant_info', 'plant_info_id', $id);
        if (empty($record)) {
            drupal_set_message(t('种植信息不存在！'), 'status', FALSE);
            return $form;
        }
        $form['#plant_info_id'] = $id;
    }
    // 判断用户角色
    if(!nonghua_user_access('plant_info', 'view', $id, !empty($record) ? $record->author_uid:0, !empty($record)?$record->farmer_id:0) ){
        drupal_set_message(t('您没有权限查看本条数据！'), 'status', FALSE);
        return $form;
    }
    $user_info = _get_user_info($user->uid);
    if (get_user_role_name($user->uid) === '农户') {
        $form['farmer_id'] = array(
            '#type' => 'hidden',
            '#value' => $user->uid,
        );
    } else {//农户服务人员
        _insert_farmer_select_info($form,$form_state,isset($record) && !empty($record)?$record:'');
    }
    $form['basic_info'] = array(
//    '#type' => 'fieldset',
//    '#title' => '基础信息',
//    '#collapsed' => true,
//    '#collapsible' => true,
    );
    $form['submit_id'] = array(
        '#prefix' => '<div id="add_fertilizer_extra_submit-wrapper-div">',
        '#suffix' => '</div>',
        '#type' => 'hidden',
        '#title' => 'ids',
    );
    insert_fertilizer_sub_info($form, $form_state, "fertilization_info");
    $form['dif_column_id'] = array(
        '#type' => 'hidden',
        '#title' => 'id',
        '#default_value' => !empty($record) ? $record->plant_info_id : ''
    );

    $form['basic_info']['plant']= _insert_plant_selection_form($form,$form_state,!empty($record) ? $record->plant_id:'');
    $perennial_options = array(1 => '一年生',2 => '多年生');
    if(!empty($record)){
        $form['#perennial'] = $record->perennial?$record->perennial:1;
    }
    $form['basic_info']['perennial'] = array(
        '#type' => 'radios',
        '#title' => '一年生/多年生',
        '#default_value' => !empty($record) ? $record->perennial:1,
        '#options' => $perennial_options,
        '#attributes'=>array('name'=>'perennial')

    );
    $form['basic_info']['sow_date'] = array(
        '#title' => '播种日期',
        '#type' => 'metercomm_date',
        '#default_value' => _date_db_2_form(!empty($record) ? $record->sow_date : ''),
        '#required' => TRUE,
    );

    $form['basic_info']['harvest_date'] = array(
        '#title' => '收获日期',
        '#type' => 'metercomm_date',
        '#default_value' => _date_db_2_form(!empty($record) ? $record->harvest_date : ''),
        '#required' => TRUE,
    );
    insert_special_activities($form,$form_state,isset($record) && !empty($record)?$record:'');
    $form['basic_info']['plant_area'] = array(
        '#type' => 'textfield',
        '#title' => '种植面积（亩）',
        '#default_value' => !empty($record) ? $record->plant_area : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );

    $form['basic_info']['seed'] = array(
        '#type' => 'textfield',
        '#title' => '种子种类',
        '#default_value' => !empty($record) ? $record->seed : '',
        '#size' => 32,
        '#maxlength' => 20,
    );

    $form['basic_info']['plant_space'] = array(
        '#type' => 'textfield',
        '#title' => '株距（厘米）',
        '#default_value' => !empty($record) ? $record->plant_space : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );

    $form['basic_info']['row_space'] = array(
        '#type' => 'textfield',
        '#title' => '行距（厘米）',
        '#default_value' => !empty($record) ? $record->row_space : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );

    $form['basic_info']['irrigation'] = array(
        '#type' => 'textfield',
        '#title' => '灌溉方式',
        '#default_value' => !empty($record) ? $record->irrigation : '',
        '#size' => 32,
        '#maxlength' => 10,
    );

    $form['economy_info'] = array(
//    '#type' => 'fieldset',
//    '#title' => '经济效益',
//    '#collapsed' => true,
//    '#collapsible' => true,
    );
    $form['economy_info']['demonstration_area'] = array(
        '#type' => 'textfield',
        '#title' => '示范面积',
        '#default_value' => !empty($record) ? $record->demonstration_area : '',
        '#size' => 32,
        '#maxlength' => 10,
    );
    $form['economy_info']['sacf_fertilizer'] = array(
        '#type' => 'textfield',
        '#title' => '撒可富赠肥量',
        '#default_value' => !empty($record) ? $record->sacf_fertilizer : '',
        '#size' => 32,
        '#maxlength' => 10,
    );
    $form['economy_info']['sacf'] = array(
        '#type' => 'textfield',
        '#title' => '撒可富品种',
        '#default_value' => !empty($record) ? $record->sacf : '',
        '#size' => 32,
        '#maxlength' => 50,
    );

    $form['economy_info']['density'] = array(
        '#type' => 'textfield',
        '#title' => '密度',
        '#default_value' => !empty($record) ? $record->density : '',
        '#size' => 32,
        '#maxlength' => 10,
    );

    $form['economy_info']['seed_cost'] = array(
        '#type' => 'textfield',
        '#title' => '种子开销（元/亩）',
        '#default_value' => !empty($record) ? $record->seed_cost : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );

    $form['economy_info']['fertilizer_cost'] = array(
        '#type' => 'textfield',
        '#title' => '肥料开销（元/亩）',
        '#default_value' => !empty($record) ? $record->fertilizer_cost : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );

    $form['economy_info']['pesticide_cost'] = array(
        '#type' => 'textfield',
        '#title' => '农药开销（元/亩）',
        '#default_value' => !empty($record) ? $record->pesticide_cost : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );

    $form['economy_info']['machinery_cost'] = array(
        '#type' => 'textfield',
        '#title' => '农机开销（元/亩）',
        '#default_value' => !empty($record) ? $record->machinery_cost : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );

    $form['economy_info']['others_cost'] = array(
        '#type' => 'textfield',
        '#title' => '其他开销（元/亩）',
        '#default_value' => !empty($record) ? $record->others_cost : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );

    $form['economy_info']['unit_price'] = array(
        '#type' => 'textfield',
        '#title' => '产品单价',
        '#default_value' => !empty($record) ? $record->unit_price : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );
    $form['economy_info']['total_input'] = array(
        '#type' => 'textfield',
        '#title' => '总投入',
        '#default_value' => !empty($record) ? $record->total_input : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );
    $form['economy_info']['income'] = array(
        '#type' => 'textfield',
        '#title' => '收入',
        '#default_value' => !empty($record) ? $record->income : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );
    $form['economy_info']['net_income'] = array(
        '#type' => 'textfield',
        '#title' => '净收入',
        '#default_value' => !empty($record) ? $record->net_income : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );
    $form['economy_info']['general_yield'] = array(
        '#type' => 'textfield',
        '#title' => '一般产量（千克/亩）',
        '#default_value' => !empty($record) ? $record->general_yield : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );

    $form['economy_info']['other_yield'] = array(
        '#type' => 'textfield',
        '#title' => '其他收益（元/亩）',
        '#default_value' => !empty($record) ? $record->other_yield : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );
    $form['comments'] = array(
        '#type' => 'textarea',
        '#title' => '备注',
        '#default_value' => !empty($record) ? $record->comments : '',
        '#rows' => 2,
        '#cols' => 32,
        '#maxlength' => 100,
        '#attributes'=>array('placeholder'=>'最多输入100字。')
    );
    $form['#fertilization'] = array("#markup" => fertilization_list('fertilization_info', 'plant_info_id', $id));

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => '提交',
        '#access' => nonghua_user_access('plant_info', 'edit', $id, !empty($record) ? $record->author_uid:0, !empty($record)?$record->farmer_id:0)
    );
    return $form;
}

function plant_info_edit_form_validate($form, &$form_state)
{
    if (empty($form_state['values']['farmer_id'])) {
        form_set_error('farmer_name', '必须选择 农户');
    }

    if (!empty($form_state['values']['plant_area'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['plant_area']) || (strlen(explode('.', $form_state['values']['plant_area'])[0]) > 8)) {
            form_set_error('plant_area', "种植面积格式错误");
        }
    }
    if (!empty($form_state['values']['plant_space'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['plant_space']) || (strlen(explode('.', $form_state['values']['plant_space'])[0]) > 8)) {
            form_set_error('plant_space', "株距格式错误");
        }
    }
    if (!empty($form_state['values']['row_space'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['row_space']) || (strlen(explode('.', $form_state['values']['row_space'])[0]) > 8)) {
            form_set_error('row_space', "行距格式错误");
        }
    }
    if (!empty($form_state['values']['seed_cost'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['seed_cost']) || (strlen(explode('.', $form_state['values']['seed_cost'])[0]) > 8)) {
            form_set_error('seed_cost', "种子开销格式错误");
        }
    }
    if (!empty($form_state['values']['fertilizer_cost'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['fertilizer_cost']) || (strlen(explode('.', $form_state['values']['fertilizer_cost'])[0]) > 8)) {
            form_set_error('fertilizer_cost', "肥料开销格式错误");
        }
    }
    if (!empty($form_state['values']['pesticide_cost'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['pesticide_cost']) || (strlen(explode('.', $form_state['values']['pesticide_cost'])[0]) > 8)) {
            form_set_error('pesticide_cost', "农药开销格式错误");
        }
    }
    if (!empty($form_state['values']['machinery_cost'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['machinery_cost']) || (strlen(explode('.', $form_state['values']['machinery_cost'])[0]) > 8)) {
            form_set_error('machinery_cost', "农机开销格式错误");
        }
    }
    if (!empty($form_state['values']['others_cost'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['others_cost']) || (strlen(explode('.', $form_state['values']['others_cost'])[0]) > 8)) {
            form_set_error('others_cost', "其他开销格式错误");
        }
    }
    if (!empty($form_state['values']['general_yield'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['general_yield']) || (strlen(explode('.', $form_state['values']['general_yield'])[0]) > 8)) {
            form_set_error('general_yield', "一般产量格式错误");
        }
    }
    if (!empty($form_state['values']['other_yield'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['other_yield']) || (strlen(explode('.', $form_state['values']['other_yield'])[0]) > 8)) {
            form_set_error('other_yield', "其他收益格式错误");
        }
    }
    if (!empty($form_state['values']['demonstration_area'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['demonstration_area']) || (strlen(explode('.', $form_state['values']['demonstration_area'])[0]) > 8)) {
            form_set_error('demonstration_area', "示范面积格式错误");
        }
    }
    if (!empty($form_state['values']['sacf_fertilizer'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['sacf_fertilizer']) || (strlen(explode('.', $form_state['values']['sacf_fertilizer'])[0]) > 8)) {
            form_set_error('sacf_fertilizer', "撒可富赠肥量格式错误");
        }
    }
    if (!empty($form_state['values']['density'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['density']) || (strlen(explode('.', $form_state['values']['density'])[0]) > 8)) {
            form_set_error('density', "密度格式错误");
        }
    }
    if (!empty($form_state['values']['unit_price'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['unit_price']) || (strlen(explode('.', $form_state['values']['unit_price'])[0]) > 8)) {
            form_set_error('unit_price', "产品单价格式错误");
        }
    }
    if (!empty($form_state['values']['total_input'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['total_input']) || (strlen(explode('.', $form_state['values']['total_input'])[0]) > 8)) {
            form_set_error('total_input', "总投入格式错误");
        }
    }
    if (!empty($form_state['values']['income'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['income']) || (strlen(explode('.', $form_state['values']['income'])[0]) > 8)) {
            form_set_error('income', "收入格式错误");
        }
    }
    if (!empty($form_state['values']['net_income'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['net_income']) || (strlen(explode('.', $form_state['values']['net_income'])[0]) > 8)) {
            form_set_error('net_income', "净收入格式错误");
        }
    }
    if(!empty($form_state['values']['plant'])){
        $plant_id = get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant'],false);
        if(empty($plant_id)){
            form_set_error('plant', "作物信息不存在！");
        }
    }

}

function plant_info_edit_form_submit($form, &$form_state)
{
    global $user;
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    clear_search_autocomplete_cach();
    if (arg(2) == 'add') {
        $nid = db_insert('plant_info')
            ->fields(array(
                'farmer_id' => $form_state['values']['farmer_id'],
                'plant_id' => get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant'],false),
                'sow_date' => _date_form_2_db($form_state['values']['sow_date']),
                'harvest_date' => _date_form_2_db($form_state['values']['harvest_date']),
                'perennial' => $form_state['values']['perennial'],
                'special_activities_id'=>get_id_from_string_field('special_activities','special_activities_id','title',$form_state['values']['special_activities']),
                'seed' => $form_state['values']['seed'],
                'irrigation' => $form_state['values']['irrigation'],
                'plant_area' => _empty_2_zero($form_state['values']['plant_area']),
                'plant_space' => _empty_2_zero($form_state['values']['plant_space']),
                'row_space' => _empty_2_zero($form_state['values']['row_space']),
                'general_yield' => _empty_2_zero($form_state['values']['general_yield']),
                'other_yield' => _empty_2_zero($form_state['values']['other_yield']),
                'seed_cost' => _empty_2_zero($form_state['values']['seed_cost']),
                'fertilizer_cost' => _empty_2_zero($form_state['values']['fertilizer_cost']),
                'pesticide_cost' => _empty_2_zero($form_state['values']['pesticide_cost']),
                'machinery_cost' => _empty_2_zero($form_state['values']['machinery_cost']),
                'others_cost' => _empty_2_zero($form_state['values']['others_cost']),
                'demonstration_area' => _empty_2_zero($form_state['values']['demonstration_area']),
                'sacf' => $form_state['values']['sacf'],
                'sacf_fertilizer' => _empty_2_zero($form_state['values']['sacf_fertilizer']),
                'density' => _empty_2_zero($form_state['values']['density']),
                'unit_price' => _empty_2_zero($form_state['values']['unit_price']),
                'total_input' => _empty_2_zero($form_state['values']['total_input']),
                'income' => _empty_2_zero($form_state['values']['income']),
                'net_income' => _empty_2_zero($form_state['values']['net_income']),
                'comments' => $form_state['values']['comments'],
                'author_uid' => $user->uid,
                'timestamp' => time(),
            ))
            ->execute();
        if ($nid > 0) {
            $ids = explode(',', $form_state['values']['submit_id']);
            foreach ($ids as $key => $val) {
                $res = db_update('fertilization_info')
                    ->fields(array(
                        'plant_info_id' => $nid,
//                        'author_uid' => $user->uid,
                        'timestamp' => time(),
                    ))
                    ->condition('id', $val, '=')
                    ->execute();
            }
            drupal_set_message(t('添加成功！'), 'status', FALSE);
            if(!empty($_GET['farmer_id'])){
                drupal_goto('farmer/plant_info/add/'.$nid,array('query' => array('farmer_id' => $_GET['farmer_id'])));
            }
            if(!empty($_GET['addr_id'])){
                drupal_goto('farmer/plant_info/list',array('query' => array('addr_id' => $_GET['addr_id'])));
            }
            drupal_goto('farmer/plant_info/add/'.$nid);
        }
    } else {
        $nid = db_update('plant_info')
            ->fields(array(
                'farmer_id' => $form_state['values']['farmer_id'],
                'plant_id' => get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['plant'],false),
                'sow_date' => _date_form_2_db($form_state['values']['sow_date']),
                'perennial' => $form_state['values']['perennial'],
                'harvest_date' => _date_form_2_db($form_state['values']['harvest_date']),
                'special_activities_id'=>get_id_from_string_field('special_activities','special_activities_id','title',$form_state['values']['special_activities']),
                'seed' => $form_state['values']['seed'],
                'irrigation' => $form_state['values']['irrigation'],
                'plant_area' => _empty_2_zero($form_state['values']['plant_area']),
                'plant_space' => _empty_2_zero($form_state['values']['plant_space']),
                'row_space' => _empty_2_zero($form_state['values']['row_space']),
                'general_yield' => _empty_2_zero($form_state['values']['general_yield']),
                'other_yield' => _empty_2_zero($form_state['values']['other_yield']),
                'seed_cost' => _empty_2_zero($form_state['values']['seed_cost']),
                'fertilizer_cost' => _empty_2_zero($form_state['values']['fertilizer_cost']),
                'pesticide_cost' => _empty_2_zero($form_state['values']['pesticide_cost']),
                'machinery_cost' => _empty_2_zero($form_state['values']['machinery_cost']),
                'others_cost' => _empty_2_zero($form_state['values']['others_cost']),
                'demonstration_area' => _empty_2_zero($form_state['values']['demonstration_area']),
                'sacf' => $form_state['values']['sacf'],
                'sacf_fertilizer' => _empty_2_zero($form_state['values']['sacf_fertilizer']),
                'density' => _empty_2_zero($form_state['values']['density']),
                'unit_price' => _empty_2_zero($form_state['values']['unit_price']),
                'total_input' => _empty_2_zero($form_state['values']['total_input']),
                'income' => _empty_2_zero($form_state['values']['income']),
                'net_income' => _empty_2_zero($form_state['values']['net_income']),
                'comments' => $form_state['values']['comments'],
//                'author_uid' => $user->uid,
                'timestamp' => time(),
            ))
            ->condition('plant_info_id', $id, '=')
            ->execute();
        if ($nid > 0) {
            drupal_set_message(t('修改成功！'), 'status', FALSE);
        }
        if(!empty($_GET['farmer_id'])){
            drupal_goto('farmer/plant_info/list',array('query' => array('farmer_id' => $_GET['farmer_id'])));
        }
        if(!empty($_GET['addr_id'])){
            drupal_goto('farmer/plant_info/list',array('query' => array('addr_id' => $_GET['addr_id'])));
        }
    }
}

